<?php
/**
 * 接口请求
 * ============================================================================
 * 网站地址: http://www.pcfcms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小潘 <1131680521@qq.com>
 * Date: 2019-12-21
 */
namespace app\api\controller;
use think\facade\Db;
use think\facade\Cache;
use think\facade\Request;
use think\facade\Session;
use think\captcha\facade\Captcha;
class Ajax extends Base
{
    public function initialize() {
        parent::initialize();
    }

    // 内容页浏览量的自增接口
    public function arcclick(){
        if (Request::isAjax()) {
            $aid = input('aid/d', 0);
            $click = 0;
            if (empty($aid)) {
                return $click;
            }
            if ($aid > 0) {
                Db::name('archives')->where('aid', $aid)->inc('click')->update();
                $click = Db::name('archives')->where('aid',$aid)->value('click');
            }
            return $click;
        }
    }

    // 获取表单数据信息
    public function form_submit(){
        $form_id = input('post.form_id/d');
        if (Request::isPost() && !empty($form_id))
        {
            $map = [];
            $post = input('post.');
            $ip = clientIP();
            $map[] = ['ip','=',$ip];
            $map[] = ['form_id','=',$form_id];
            $map[] = ['add_time','<',time() - 60];
            $count = Db::name('guestbook_list')->where($map)->count('list_id');
            if ($count > 0 && 1>1) {
                $result = ['status' => false, 'msg' => '同一个IP在60秒之内不能重复提交！'];
                return json($result);
            }            
            $p = Db::name('guestbook')->where('id',$form_id)->find();
            if ($p['status'] == 0) {
                $result = ['status' => false, 'msg' => '留功能未开启！'];
                return json($result);
            }
            if ($p['need_login'] ==1) {
                $result = ['status' => false, 'msg' => '需要登陆，才可以提交！'];
                return json($result);
            }  
            $city = getCity();
            $newData = array(
                'form_id'    => $form_id,
                'ip'    => $ip,
                'city' => $city,
                'add_time'  => time(),
            );
            $data = array_merge($post, $newData);
            if(Session::get('__token__') != $post['__token__']) {
                $result = ['status' => false, 'msg' => 'token验证失败！'];
                return json($result);
            }else{
                Session::set('__token__','');
            }
            unset($data['__token__']);
            $formlistRow = [];
            // 处理是否重复表单数据的提交
            $formdata = $data;
            foreach ($formdata as $key => $val) {
                if (in_array($key, ['form_id']) || preg_match('/^attr_(\d+)$/i', $key)) {
                    continue;
                }
                unset($formdata[$key]);
            }
            $md5data = md5(serialize($formdata));
            $newData['md5data'] = $md5data;
            $formlistRow = Db::name('guestbook_list')->field('list_id')->where('md5data',$md5data)->find();
            if (empty($formlistRow)) { 
                // 非重复表单的才能写入数据库
                $list_id = Db::name('guestbook_list')->insertGetId($newData);
                if ($list_id > 0) {
                    $this->saveFormValue($list_id, $form_id);
                    $result = ['status' => true, 'msg' => '提交成功'];
                    return json($result);                    
                }else{
                    $result = ['status' => true, 'msg' => '提交失败'];
                    return json($result);  
                }
            } else {
                // 存在重复数据的表单，将在后台显示在最前面
                $list_id = $formlistRow['list_id'];
                Db::name('guestbook_list')->where('list_id',$list_id)->update([
                    'is_read'   => 0,
                    'update_time'   => time(),
                ]);
                $result = ['status' => true, 'msg' => '提交成功'];
                return json($result);   
            }
        }
    }
    
    // 给指定报名信息添加表单值到 form_value
    private function saveFormValue($list_id, $form_id){    
        $post = input("post.");
        foreach($post as $key => $val)
        {
            if(!strstr($key, 'attr_')){
                continue;
            } 
            $attr_id = str_replace('attr_', '', $key);
            is_array($val) && $val = implode(',', $val);
            $val = trim($val);
            $attr_value = stripslashes(filter_line_return($val, '。'));
            $adddata = array(
                'form_id'   => $form_id,
                'list_id'   => $list_id,
                'attr_id'   => intval($attr_id),
                'attr_value'   => $attr_value,
                'add_time'   => time(),
            );
            Db::name('guestbook_value')->save($adddata);
        }
    }
    
    // 验证码
    public function captcha(){
        ob_clean();
        return Captcha::create('captcha');
    }

    // 检验会员登录
    public function check_user()
    {
        if (Request::isPost()) {
            $type = input('param.type/s', 'default');
            $img = input('param.img/s');
            if ('login' == $type) {
                $users_id = Session::get('pcfcms_users_id');
                if (!empty($users_id)) {
                    $currentstyle = input('param.currentstyle/s');
                    $users = Db::name('users')->field('username,nickname,litpic')->where('id', $users_id)->find();
                    if (!empty($users)) {
                        $nickname = $users['nickname'];
                        if (empty($nickname)) {
                            $nickname = $users['username'];
                        }
                        $head_pic = get_head_pic($users['litpic']);
                        if ('on' == $img) {
                            $users['html'] = "<img class='{$currentstyle}' alt='{$nickname}' src='{$head_pic}'/>";
                        } else {
                            $users['html'] = $nickname;
                        }
                        $users['pcfcms_is_login'] = 1;
                        $result = ['status' => true, 'msg' => '请求成功','data'=> $users,'url'=>"/user.users/users_center.html"];
                        return json($result);
                    }
                }
                $result = ['status' => true, 'msg' => '请先登录','data'=>['pcfcms_is_login'=>0]];
                return json($result);
            }
            else if ('reg' == $type){
                if (Session::get('pcfcms_users_id') > 0) {
                    $users['pcfcms_is_login'] = 1;
                } else {
                    $users['pcfcms_is_login'] = 0;
                }
                $result = ['status' => true, 'msg' => '请求成功','data'=>$users];
                return json($result);
            }
            else if ('logout' == $type){
                if (Session::get('pcfcms_users_id') > 0) {
                    $users['pcfcms_is_login'] = 1;
                } else {
                    $users['pcfcms_is_login'] = 0;
                }
                $result = ['status' => true, 'msg' => '请求成功','data'=>$users];
                return json($result);
            }
        }
        $result = ['status' => false, 'msg' => '访问错误'];
        return json($result);
    }

    
}